<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use app\BaseController;
use app\common\service\AgentApiService;
use OSS\OssClient;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureVideo;
use app\admin\model\FigureVideoBackground;
use app\admin\model\FigureVoiceTwin;
use app\common\service\ApiService;
use FFMpeg\FFMpeg;
use app\admin\model\FigureCompositeSound;
use app\admin\model\FigureAvatar;

/**
 * 视频剪辑操作
 *
 * @author Administrator
 *
 */
class Video extends BaseController
{

    /**
     * 默认音色
     * http://aigc.weijuyunke.cn/mobile/video/timbreList
     */
    public function timbreList()
    {
        try {

            $apiService = new ApiService();
            $result = $apiService->timbreList();

            if (isset($result['code']) && $result['code'] == 1) {
                return result(0, 'success', $result['data']);
            } else {
                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 音频列表
     * http://aigc.weijuyunke.cn/mobile/video/soundList
     *
     * @param
     *            uid 用户id
     * @param
     *            status 1-最新 2-历史
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function soundList()
    {
        try {

            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }


            /*    $list = FigureCompositeSound::where("uid", $uid
                )->where("_id != '' AND url = '' ")->where($where)->select();

                if ($list) {
                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }

                   foreach ($list as $key => $value) {
                        $result = $apiService->soundDetail($value['_id']);

                        if (isset($result['code']) && $result['code'] == 1) {

                            if ($result['data']) {
                                FigureCompositeSound::where("id", $value['id'])->save([
                                    'url' => isset($result['data']['url']) ? $result['data']['url'] : ''
                                ]);
                            }
                        }
                    }
                }*/

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where['uid'] = $uid;
            $where['is_batch'] = 0;
            // $where = " uid = {$uid} and is_batch = 0   ";
            $voice_channel = input('voice_channel');
            if ($voice_channel) {
                $where['voice_channel'] = $voice_channel;
                //  $where .= "and  voice_channel ={$voice_channel}";
            }

            if (!empty(input('status'))) {
                $status = input('status');
                $where['status'] = $status;
                //    $where .= " AND status = {$status} ";
            }

            $total = FigureCompositeSound::where($where)->count();
            if ($total) {
                $list = FigureCompositeSound::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }

            $totalPage = ceil($total / $psize);

            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }
    /**
     * 音频刷新
     * http://aigc.weijuyunke.cn/mobile/video/soundRefresh
     *
     * @param
     *            uid 用户id
     * @param
     *            sound_id 音频id
     */
    public function soundRefresh()
    {
        try {

            $uid = input('uid');
            $sound_id = input('sound_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $sound = FigureCompositeSound::where([
                'uid' => $uid,
                'id' => $sound_id
            ])->find();
            if (empty($sound)) {
                return result(-1, '音频不存在');
            }

            $url = "";

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->soundDetail($sound['_id']);

            if (isset($result['code']) && $result['code'] == 1) {

                if (isset($result['data'])) {
                    FigureCompositeSound::where("id", $sound['id'])->save([
                        'url' => isset($result['data']['url']) ? $result['data']['url'] : ''
                    ]);

                    if (!empty($result['data']['url'])) {
                        $url = $result['data']['url'];
                    }
                }
            }

            return result(0, 'success', $url);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 音频删除
     * http://aigc.weijuyunke.cn/mobile/video/soundDel
     *
     * @param
     *            uid 用户id
     * @param
     *            sound_id 音频id
     */
    public function soundDel()
    {
        try {
            $uid = input('uid');
            $sound_id = input('sound_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $sound = FigureCompositeSound::where([
                'uid' => $uid,
                'id' => $sound_id
            ])->find();
            if (empty($sound)) {
                return result(-1, '音频不存在');
            }

            $sound->delete();
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 生成音频（标准）
     * http://aigc.weijuyunke.cn/mobile/video/sendTts
     *
     * @param
     *            uid 用户id
     * @param
     *            msg 文本
     * @param
     *            name 名称
     * @param
     *            speechRate 语速，取值范围：-500~500，默认0
     * @param
     *            pitchRate 语调，取值范围：-500~500，默认0
     * @param
     *            voice_type 1-默认音色；2-自定义音色
     * @param
     *            voice_id 语音id 从 声音克隆 返回中获取id
     */
    public function sendTts()

    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $msg = input('msg');
            if (empty($msg)) {
                return result(-1, '请输入文本内容');
            }

            $voice_type = input('voice_type');
            if (empty($voice_type)) {
                return result(-1, 'voice_type必传');
            }

            $voice_id = input('voice_id');
            if (empty($voice_id)) {
                return result(-1, 'voice_id必传');
            }

            $name = "";
            if ($voice_type == 1) {
                $name = !empty(input('name')) ? input('name') : date('ymd') . rand(999, 9999);
            } elseif ($voice_type == 2) {
                $voice = FigureVoiceTwin::where([
                    'uid' => $uid,
                    'id' => $voice_id
                ])->find();

                if (empty($voice)) {
                    return result(-1, 'voice不存在');
                }

                $name = $voice['name'];
            }

            $data = array(
                'msg' => $msg,
                'name' => $name,
                'voice_type' => $voice_type,
                'voice_id' => isset($voice) ? $voice['_id'] : $voice_id
            );

            if (input('speechRate') != '') {
                $data['speechRate'] = input('speechRate');
            }

            if (input('pitchRate') != '') {
                $data['pitchRate'] = input('pitchRate');
            }

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->sendTts($data);

            if (isset($result['code']) && $result['code'] == 1) {

                $sound = new FigureCompositeSound();
                $sound->save([
                    'uid' => $uid,
                    'voice_type' => $voice_type,
                    'voice_id' => $voice_id,
                    'name' => $name,
                    'text' => $msg,
                    'status' => 1,
                    '_id' => $result['data']['id']
                ]);

                return result(0, '提交成功', $sound['id']);
            } else {
                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频生成
     * http://aigc.weijuyunke.cn/mobile/video/generate
     *
     * @param
     *            uid 用户id
     * @param
     *            name 视频标题
     * @param
     *            avatar_id 形象id
     * @param
     *            sound_id 音频id
     * @param
     *            audio_src 音频链接 高保真传
     */
    public function generate()
    {
        try {

            $request = $this->request;
            $param = $request->param();

            $uid = $param['uid'];
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            if (empty($param['avatar_id']))
                return result(-1, 'avatar_id不能为空');

            if (empty($param['sound_id']) && empty($param['audio_src'])) {
                return result(-1, 'sound_id/audio_src必传');
            }

            $avatar = FigureAvatar::where([
                'uid' => $uid,
                'id' => $param['avatar_id']
            ])->find();
            if (empty($avatar)) {
                return result(-1, 'avatar不存在');
            }

            $audio_src = "";
            if (!empty($param['sound_id'])) {
                $sound = FigureCompositeSound::where([
                    'uid' => $uid,
                    'id' => $param['sound_id']
                ])->find();
                if (empty($sound)) {
                    return result(-1, 'sound不存在');
                }
                if (empty($sound['url'])) {
                    return result(-1, 'sound生成中');
                }

                $duration = ceil($sound['duration'] ? $sound['duration'] : getDuration(1, $sound['url']));
                $audio_src = $sound['url'];
            } else {
                $audio_src = $param['audio_src'];
                $duration = ceil(getDuration(1, $audio_src));
            }

            if ($duration == 0) {
                return result(-1, '音频错误');
            }

            $tally = (float)sysconfig('tally', 'video_deduct');
            $money = (float)$tally * $duration;

            if (!$user['is_member']) {

                if ($user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            } else {

                if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            }
            $log_no = getPayNo('VD');
            $params = array(
                'uid' => $uid,
                'duration' => $duration,
                'anchor_type' => 1,
                'name' => $param['name'],
                'avatar_id' => $param['avatar_id'],
                'audio_src' => $audio_src,
                'log_no' => $log_no
            );


            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
                $result = $apiService->generate([
                    'name' => $params['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $audio_src
                ]);
            } else {
                $apiService = new ApiService();
                $result = $apiService->generate([
                    'title' => $params['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $audio_src
                ]);
            }
            if (isset($result['code']) && $result['code'] == 1) {

                if (!empty($sound)) {
                    $sound->save([
                        'status' => 2,
                        'duration' => $duration
                    ]);
                }

                $video = new FigureVideo();
                $video->save($params);


                $video->save([
                    '_id' => $result['data']['id'],
                    'current_status' => $result['data']['current_status']
                ]);
                $FigureWayName = new \app\admin\model\FigureWayName();
                $FigureWayNameInfo = $FigureWayName
                    ->where(['id' => 1])
                    ->find();
                user_balance_used($uid, $log_no, 2, 6, $result['data']['duration'], $FigureWayNameInfo['reception'] . '创作');

                return result(0, '生成成功');
            } else {

                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage(), $e->getTrace());
            exit();
        }
    }

    /**
     * 视频列表
     * http://aigc.weijuyunke.cn/mobile/video/videoList
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function videoList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where = " uid = {$uid} ";

            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%'";
            }

            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = {$type} ";
            }

            if (!empty(input('current_status'))) {
                $current_status = input('current_status');

                if ($current_status == 'init') {
                    $where .= " AND current_status != 'success' AND current_status != 'fail'  ";
                } elseif ($current_status == 'success') {
                    $where .= " AND (current_status = 'success' OR current_status = 'copy' )  ";
                } else {
                    $where .= " AND current_status = '{$current_status}'";
                }
            }

            $total = FigureVideo::where($where)->count();
            if ($total) {
                $list = FigureVideo::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

                // foreach ($list as $key => $value) {

                // $where = " type = 1 AND video_id = {$value['id']}";

                // $play = FigureVideoRepost::where($where)->sum('total_play');
                // $like = FigureVideoRepost::where($where)->sum('total_like');
                // $comment = FigureVideoRepost::where($where)->sum('total_comment');

                // $list[$key]['play'] = empty($play) ? 0 : $play;
                // $list[$key]['like'] = empty($like) ? 0 : $like;
                // $list[$key]['comment'] = empty($comment) ? 0 : $comment;
                // }
            } else {
                $list = array();
            }

            $totalPage = ceil($total / $psize);

            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频删除
     * http://aigc.weijuyunke.cn/mobile/video/videoDel
     *
     * @param
     *            uid 用户id
     * @param
     *            video_id 视频id
     */
    public function videoDel()
    {
        try {
            $uid = input('uid');
            $video_id = input('video_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $video = FigureVideo::where([
                'uid' => $uid,
                'id' => $video_id
            ])->find();
            if (empty($video)) {
                return result(-1, '视频不存在');
            }

            if (!empty($video['local_url'])) {


                $parsedUrl = parse_url($video['local_url']);
                $sourceFilePath = substr($parsedUrl['path'], 1);
                $upload = sysconfig('upload');
                $sourceAccessKeyId = $upload['alioss_access_key_id'];
                $sourceAccessKeySecret = $upload['alioss_access_key_secret'];
                $sourceEndpoint = $upload['alioss_endpoint'];
                $sourceBucket = $upload['alioss_bucket'];

                $OssClient = new OssClient($sourceAccessKeyId, $sourceAccessKeySecret, $sourceEndpoint);
                $OssClient->deleteObject($sourceBucket, $sourceFilePath);


                $urlTemp = explode("/", $video['local_url']);
                $urlName = end($urlTemp);

                $coverTemp = explode("/", $video['local_cover']);
                $coverName = end($coverTemp);

                $url_path = root_path() . 'public/uploads/video/' . $urlName;
                $cover_path = root_path() . 'public/uploads/video-cover/' . $coverName;

                if (is_file($url_path)) {
                    unlink($url_path);
                }
                if (is_file($cover_path)) {
                    unlink($cover_path);
                }
            }

            $video->delete();

            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 下载视频
     * http://aigc.weijuyunke.cn/mobile/video/toLocal
     *
     * @param
     *            uid 用户id
     * @param
     *            video_id 视频id
     */
    public function toLocal()
    {
        try {

            set_time_limit(0);
            ini_set("memory_limit", "1024M");
            ini_set('max_execution_time', 1000);

            $uid = input('uid');
            $video_id = input('video_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $video = FigureVideo::where([
                'uid' => $uid,
                'id' => $video_id
            ])->find();
            if (empty($video)) {
                return result(-1, '视频不存在');
            }

            if (empty($video['result'])) {
                return result(-1, '视频未生成成功');
            }

            if (!empty($video['local_url'])) {
                return result(0, 'success', [
                    'local_cover' => $video['local_cover'],
                    'local_url' => $video['local_url']
                ]);
            }

            $start = time();

            $name = time() . rand(999, 9999);

            $path = root_path() . 'public/uploads/video';

            if (!is_dir($path)) {
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }

            $path .= '/video-' . $name . '.mp4';

            // 使用cURL下载视频
            $ch = curl_init($video['result']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoData = curl_exec($ch);
            curl_close($ch);

            // 将视频数据保存到本地文件
            $videoFile = fopen($path, 'wb');
            fwrite($videoFile, $videoData);

            $domain = request()->domain();
            $paths = $domain . "/uploads/video/video-" . $name . '.mp4';

            $cover_path = root_path() . 'public/uploads/video-cover';

            if (!is_dir($cover_path)) {
                mkdir(iconv("UTF-8", "GBK", $cover_path), 0777, true);
            }

            $cover_path .= '/video-cover-' . $name . '.jpg';

            if ($video['result_cover']) {
                $ch = curl_init($video['result_cover']);
            } else {
                $ch = curl_init($video['result'] . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto");
            }

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $coverData = curl_exec($ch);
            curl_close($ch);

            // 将视频数据保存到本地文件
            $coverFile = fopen($cover_path, 'wb');
            fwrite($coverFile, $coverData);

            fclose($coverFile);
            fclose($videoFile);

            $domain = request()->domain();
            $cover = $domain . "/uploads/video-cover/video-cover-" . $name . '.jpg';

            $video->save([
                'is_local' => 1,
                'local_url' => $paths,
                'local_cover' => $cover,
                'local_time' => time()
            ]);

            $end = time();
            return result(0, 'success', [
                'start' => $start,
                'end' => $end,
                'local_cover' => $cover,
                'local_url' => $paths
            ]);
        } catch (\Exception $e) {
            Log::write("toLocal 失败" . json_encode($e->getTrace()), 'info');
            return result(-1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * 视频详情
     * http://aigc.weijuyunke.cn/mobile/video/videoDetail
     *
     * @param
     *            video_id 视频id
     */
    public function videoDetail()
    {
        try {

            set_time_limit(0);
            ini_set("memory_limit", "1024M");
            ini_set('max_execution_time', 1000);

            $video_id = input('video_id');

            $video = FigureVideo::where('id', $video_id)->find();
            if (empty($video)) {
                return result(-1, '视频不存在');
            }

            if (empty($video['result'])) {
                return result(-1, '视频未生成成功');
            }

            if (!empty($video['local_url'])) {
                return result(0, 'success', $video);
            }

            $start = time();

            $name = time() . rand(999, 9999);

            $path = root_path() . 'public/uploads/video';

            if (!is_dir($path)) {
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }

            $path .= '/video-' . $name . '.mp4';

            // 使用cURL下载视频
            $ch = curl_init($video['result']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoData = curl_exec($ch);
            curl_close($ch);

            // 将视频数据保存到本地文件
            $videoFile = fopen($path, 'wb');
            fwrite($videoFile, $videoData);

            fclose($videoFile);

            $domain = request()->domain();
            $paths = $domain . "/uploads/video/video-" . $name . '.mp4';

            $cover_path = root_path() . 'public/uploads/video-cover';

            if (!is_dir($cover_path)) {
                mkdir(iconv("UTF-8", "GBK", $cover_path), 0777, true);
            }

            $cover_path .= '/video-cover-' . $name . '.jpg';

            if ($video['result_cover']) {
                $ch = curl_init($video['result_cover']);
            } else {
                $ch = curl_init($video['result'] . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto");
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $coverData = curl_exec($ch);
            curl_close($ch);

            // 将视频数据保存到本地文件
            $coverFile = fopen($cover_path, 'wb');
            fwrite($coverFile, $coverData);

            fclose($coverFile);

            $domain = request()->domain();
            $cover = $domain . "/uploads/video-cover/video-cover-" . $name . '.jpg';

            $video->save([
                'is_local' => 1,
                'local_url' => $paths,
                'local_cover' => $cover,
                'local_time' => time()
            ]);

            return result(0, 'success', $video);
        } catch (\Exception $e) {
            Log::write("videoDetail 失败" . json_encode($e->getTrace()), 'info');
            return result(-1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * 视频生成
     * http://aigc.weijuyunke.cn/mobile/video/generate
     *
     * @param
     *            uid 用户id
     * @param
     *            name 视频标题
     * @param
     *            avatar_id 形象id
     * @param
     *            sound_id 音频id
     * @param
     *            audio_src 音频链接 高保真传
     */
    public function generateTwo()
    {
        try {

            $request = $this->request;
            $param = $request->param();
            validate(\app\mobile\validate\Composite::class)->check($param);

            $uid = $param['uid'];

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            if (empty($param['sound_id']))
                return result(-1, 'sound_id不能为空');

            if (empty($param['image_id']))
                return result(-1, 'image_id不能为空');

            $sound = FigureCompositeSound::where([
                'uid' => $uid,
                'id' => $param['sound_id']
            ])->find();
            if (empty($sound)) {
                return result(-1, 'sound不存在');
            }

            $image = FigureAvatar::where([
                'uid' => $uid,
                'id' => $param['image_id']
            ])->find();
            if (empty($image)) {
                return result(-1, 'image不存在');
            }

            $duration = ceil(getDuration(1, $sound['url']));

            if ($duration == 0) {
                return result(-1, '音频错误');
            }

            $tally = (float)sysconfig('tally', 'woni_video_deduct');
            $money = (float)$tally * $duration;

            if (!$user['is_member']) {
                if ($user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            } else {
                if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            }
            $log_no = getPayNo('JS');
            $params = array(
                'uid' => $uid,
                'name' => $param['name'],
                'type' => 3,
                'anchor_type' => 1,
                'image_id' => $image['_id'],
                'sound_id' => $sound['_id'],
                'duration' => $duration,
                'log_no' => $log_no
            );

            if (!empty($param['width'])) {
                $params['width'] = $param['width'];
            }

            if (!empty($param['height'])) {
                $params['height'] = $param['height'];
            }

            if (!empty($param['combination'])) {
                $params['combination'] = $param['combination'];
            }

            if (!empty($param['caption_json'])) {
                $params['caption_json'] = $param['caption_json'];
            }

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();

            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->generateTwo($params);

            if (isset($result['code']) && $result['code'] == 1) {

                $video = new FigureVideo();
                $video->save($params);


                $video->save([
                    '_id' => $result['data']['id'],
                    'current_status' => 'init'
                ]);
                $FigureWayName = new \app\admin\model\FigureWayName();
                $FigureWayNameInfo = $FigureWayName
                    ->where(['id' => 2])
                    ->find();
                user_balance_used($uid, $log_no, 2, 13, $duration, $FigureWayNameInfo['name'] . '创作');

                return result(0, '生成成功');
            } else {
                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }


    public function generateFour()
    {
        try {

            $request = $this->request;
            $param = $request->param();
            $uid = $param['uid'];
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            if (empty($param['avatar_id']))
                return result(-1, 'avatar_id不能为空');

            if (empty($param['sound_id']) && empty($param['audio_src'])) {
                return result(-1, 'sound_id/audio_src必传');
            }
            $avatar = FigureAvatar::where([
                'uid' => $uid,
                'id' => $param['avatar_id']
            ])->find();
            if (empty($avatar)) {
                return result(-1, '形象不存在');
            }


            $audio_src = "";
            if (!empty($param['sound_id'])) {
                $sound = FigureCompositeSound::where([
                    'uid' => $uid,
                    'id' => $param['sound_id']
                ])->find();
                if (empty($sound)) {
                    return result(-1, 'sound不存在');
                }
                if (empty($sound['url'])) {
                    return result(-1, 'sound生成中');
                }

                $duration = ceil($sound['duration'] ? $sound['duration'] : getDuration(1, $sound['url']));
                $audio_src = $sound['url'];
            } else {
                $audio_src = $param['audio_src'];
                $duration = ceil(getDuration(1, $audio_src));
            }

            if ($duration == 0) {
                return result(-1, '音频错误');
            }

            $tally = (float)sysconfig('tally', 'composite_deduct_four');

            $minute = ceil($duration / 60);
            $money = $minute * $tally;
            if (!$user['is_member']) {
                if ($user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            } else {
                $needDurationceil = ceil($duration / 60) * 60;
                if ($user['second_infinite'] == 0 && $user['second'] < $needDurationceil && $user['balance'] < $money) {
                    return result(-2, '余额不足，请充值');
                }
            }
            $log_no = getPayNo('VD');
            $params = array(
                'uid' => $uid,
                'duration' => $duration,
                'anchor_type' => 1,
                'name' => $param['name'],
                'avatar_id' => $param['avatar_id'],
                'audio_src' => $audio_src,
                'type' => 4,
                'log_no' => $log_no
            );

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
                $result = $apiService->fourGenerate([
                    'name' => $params['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $audio_src
                ]);
            } else {
                $apiService = new ApiService();
                $result = $apiService->fourGenerate([
                    'title' => $params['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $audio_src
                ]);
            }


            if (isset($result['code']) && $result['code'] == 1) {
                if (!empty($sound)) {
                    $sound->save([
                        'status' => 2,
                        'duration' => $duration
                    ]);
                }
                $video = new FigureVideo();
                $video->save($params);

                $video->save([
                    '_id' => $result['data']['id'],
                    'current_status' => $result['data']['current_status']
                ]);
                $FigureWayName = new \app\admin\model\FigureWayName();
                $FigureWayNameInfo = $FigureWayName
                    ->where(['id' => 4])
                    ->find();

                user_balance_used($uid, $log_no, 2, 28, ceil($result['data']['duration'] / 60), $FigureWayNameInfo['reception'] . '创作');

                return result(0, '生成中');
            } else {

                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage(), $e->getTrace());
            exit();
        }
    }


    public function generateVideo()
    {
        $request = $this->request;
        $param = $request->param();
        $uid = $param['uid'];
        $type = $param['type'];
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        /* if (empty($param['avatar_id']))
             return result(-1, 'avatar_id不能为空');*/

        if (empty($param['sound_id'])) {
            return result(-1, 'sound_id必传');
        }


        $totalMoney = 0;
        $data = [];

        $i =0;
        $params = [];
        $order_number = getPayNo('VD');
        foreach ($param['sound_id'] as $key => $value) {
            $sound = FigureCompositeSound::where([
                'uid' => $uid,
                'id' => $value
            ])->find();
            if (empty($sound)) {
                return result(-1, 'sound不存在');
            }
            if (empty($sound['url'])) {
                return result(-1, 'sound生成中');
            }
            $FigureWayName = new \app\admin\model\FigureWayName();

            $duration = ceil($sound['duration'] ? $sound['duration'] : getDuration(1, $sound['url']));


            foreach ($param['avatar_id'] as $avatarKey => $avatarValue) {
                $log_no = getPayNo('VD');
                if ($type == 1) {  // 线路1 秒收费
                    $tally = (float)sysconfig('tally', 'video_deduct');
                    $money = $tally * $duration;
                    if (!$user['is_member']) {
                        if ($user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        $user['balance'] = bcsub($user['balance'], $money, 2);
                    } else {
                        if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        if ($user['second_infinite'] == 1 && $user['second'] > $duration) {
                            $user['second'] = bcsub($user['second'], $duration, 2);
                        } else {
                            $user['balance'] = bcsub($user['balance'], $money, 2);
                        }
                    }
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 1])
                        ->find();

                } else if ($type == 2) {// 线路3 分钟收费
                    $tally = (float)sysconfig('tally', 'composite_deduct');
                    $duration = ceil($duration / 60) * 60;
                    $money = $tally * ceil($duration / 60);
                    if (!$user['is_member']) {
                        if ($user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        $user['balance'] = bcsub($user['balance'], $money, 2);
                    } else {
                        if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        if ($user['second_infinite'] == 1 && $user['second'] > $duration) {
                            $user['second'] = bcsub($user['second'], $duration, 2);
                        } else {
                            $user['balance'] = bcsub($user['balance'], $money, 2);
                        }
                    }
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 3])
                        ->find();
                } else if ($type == 3) {// 线路2秒收费

                    $tally = (float)sysconfig('tally', 'woni_video_deduct');
                    $money = $tally * $duration;
                    if (!$user['is_member']) {

                        if ($user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        $user['balance'] = bcsub($user['balance'], $money, 2);
                    } else {
                        if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        if ($user['second_infinite'] == 1 && $user['second'] > $duration) {
                            $user['second'] = bcsub($user['second'], $duration, 2);
                        } else {
                            $user['balance'] = bcsub($user['balance'], $money, 2);
                        }
                    }
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 2])
                        ->find();


                } else if ($type == 4) {// 线路4 分钟收费
                    $tally = (float)sysconfig('tally', 'composite_deduct_four');
                    $duration = ceil($duration / 60) * 60;
                    $money = $tally * ceil($duration / 60);
                    if (!$user['is_member']) {

                        if ($user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        $user['balance'] = bcsub($user['balance'], $money, 2);
                    } else {

                        if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                            return result(-2, '余额不足，请充值');
                        }
                        if ($user['second_infinite'] == 1 && $user['second'] > $duration) {
                            $user['second'] = bcsub($user['second'], $duration, 2);
                        } else {
                            $user['balance'] = bcsub($user['balance'], $money, 2);
                        }
                    }
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 4])
                        ->find();
                }


                if ($type == 2  || $type == 3){
                    $avatar = FigureAvatar::where([
                        'uid' => $uid,
                        'id' => $avatarValue['id']
                    ])->find();
                    $params[$i] = array(
                        'uid' => $uid,
                        'name' => $param['name'],
                        'type' => $param['type'],
                        'anchor_type' => 1,
                        'image_id' => $avatar['_id'],
                        'sound_id' => $sound['_id'],
                        'duration' => $duration,
                        'log_no' => $log_no,
                        'current_status' => 'wait_sent',
                        'order_number' => $order_number

                    );

                    if (!empty($avatarValue['width'])) {
                        $params[$i]['width'] = $avatarValue['width'];
                    }

                    if (!empty($avatarValue['height'])) {
                        $params[$i]['height'] = $avatarValue['height'];
                    }

                    if (!empty($avatarValue['combination'])) {
                        $params[$i]['combination'] = $avatarValue['combination'];
                    }

                    if (!empty($avatarValue['caption_json'])) {
                        $params[$i]['caption_json'] = $avatarValue['caption_json'];
                    }

                    $params[$i]['is_batch_generate'] = 1;
                }else if ($type == 1){
                    $params[$i] = array(
                        'uid' => $uid,
                        'duration' => $duration,
                        'anchor_type' => 1,
                        'name' => $param['name'],
                        'avatar_id' => $avatarValue['id'],
                        'audio_src' => $sound['audio_src'],
                        'log_no' => $log_no,
                        'order_number' => $order_number,
                        'current_status' => 'wait_sent',
                    );
                    $params[$i]['is_batch_generate'] = 1;
                }else{
                    $params[$i] = array(
                        'uid' => $uid,
                        'duration' => $duration,
                        'anchor_type' => 1,
                        'name' => $param['name'],
                        'avatar_id' => $avatarValue['id'],
                        'audio_src' => $sound['audio_src'],
                        'type' => 4,
                        'log_no' => $log_no,
                        'order_number' => $order_number,
                        'current_status' => 'wait_sent',
                    );
                    $params[$i]['is_batch_generate'] = 1;
                }

                $i ++;
            }


        }
        foreach ($params as $value) {
            $video = new FigureVideo();


            if ($type == 1) {  // 线路1 秒收费

                user_balance_used($uid, $value['log_no'], 2, 6, $value['duration'], $FigureWayNameInfo['name'] . '创作');
            } else if ($type == 2) {// 线路3 分钟收费
                user_balance_used($uid, $value['log_no'], 2, 10, ceil($value['duration'] / 60), $FigureWayNameInfo['name'] . '创作');

            } else if ($type == 3) {// 线路2秒收费
                user_balance_used($uid, $value['log_no'], 2, 13, $value['duration'], $FigureWayNameInfo['name'] . '创作');

            } else if ($type == 4) {// 线路4 分钟收费
                user_balance_used($uid, $value['log_no'], 2, 28, ceil($value['duration'] / 60), $FigureWayNameInfo['name'] . '创作');

            }
            $video->save($value);

        }
        return result(0, '生成中');

    }



}